﻿var util = require('util');
var static = require('../node static/lib/node-static');
var http = require('http');
var nowjs = require('now');

//server stuff
// Create a node-static server to serve the current directory
var file = new (static.Server)('.', { headers: { 'X-Hello': 'World!'} });

var server = http.createServer(function (request, response) {
    request.addListener('end', function () {
        //
        // Serve files!
        //
        file.serve(request, response, function (err, res) {
            if (err) { // An error as occured
                util.error("> Error serving " + request.url + " - " + err.message);
                response.writeHead(err.status, err.headers);
                response.write("404 - File not found");
                response.end();
            } else { // The file was served successfully
                util.puts("> " + request.url + " - " + res.message);
            }
        });
    });
}).listen(9000);

util.puts("> node-static is listening on http://127.0.0.1:9000");

var everyone = nowjs.initialize(server);

//end server stuff


//chat stuff
everyone.now.distributeMessage = function (msg) {
    if (msg != null && msg != "" && msg != undefined) {
        console.log(this.now.name + " : " + msg);
        everyone.now.receiveMessage(this.now.name, msg);
    }
};

//end chat stuff


//game stuff
function stock(name, EPIC, price, change) {
    this.name = name;
    this.EPIC = EPIC;
    this.price = price;
    this.change = change;
}

function userScore(username, score) {
    this.username = username;
    this.score = score;
}

var userArray = new Array();

var stockArray = new Array(
 { companyName: "Tesco", EPIC: "TSCO", unitPrice: 1, change: 4, stockQty: 0, signImg: "plus.png" },
 { companyName: "Thorntons", EPIC: "THT", unitPrice: 3, change: 4, stockQty: 0, signImg: "plus.png" },
 { companyName: "Next", EPIC: "NXT", unitPrice: 2, change: 4, stockQty: 0, signImg: "plus.png" },
 { companyName: "Argos", EPIC: "ARG", unitPrice: 4, change: 4, stockQty: 0, signImg: "plus.png" },
 { companyName: "Marks&Sp", EPIC: "MKS", unitPrice: 3, change: 4, stockQty: 0, signImg: "plus.png" },
 { companyName: "Carters", EPIC: "CRI", unitPrice: 1, change: 4, stockQty: 0, signImg: "plus.png" },
 { companyName: "ReallyLongNameCompany", EPIC: "RLNC", unitPrice: 2, change: 4, stockQty: 0, signImg: "plus.png" }
);

//initialize random stock function
//updateRandCompany();
setInterval(updateRandCompany, 10000);

//set interval á 2mín - 120000
function updateRandCompany() {
    var newUnitPrice = 1;

    //rand tölu % 2 fyrir hækka eða lækka
    var incDec = RandInt(1, 2);

    //rand tölu milli 5 og 15
    var perc = RandInt(5, 15) / 100;

    //velja fyrirtæki til að hækka eða lækka
    var randCompanyIndex = RandInt(0, stockArray.length - 1);

    if (incDec == 1) {
        newUnitPrice += ((stockArray[randCompanyIndex].unitPrice) * perc);
        stockArray[randCompanyIndex].signImg = "plus.png";
    }
    else {
        newUnitPrice -= ((stockArray[randCompanyIndex].unitPrice) * perc);
        stockArray[randCompanyIndex].signImg = "minus.png";
    }

    newUnitPrice = Math.floor(newUnitPrice);
    console.log(newUnitPrice);

    stockArray[randCompanyIndex].unitPrice += newUnitPrice;
    stockArray[randCompanyIndex].change = newUnitPrice;

    console.log(stockArray[randCompanyIndex].unitPrice);
    console.log(stockArray[randCompanyIndex].EPIC);

    everyone.now.receiveStocks(stockArray);
}

function RandInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min; //fengið að láni hjá Internetinu - skilist eftir helgi
}

everyone.now.customerInfluence = function (EPIC, numStocksBought, action) {
    var index = 0;

    for (var i = 0; i < stockArray.length; i++) {
        if (EPIC == stockArray[i].EPIC)
            index = i;
    }

    var newUnitPrice = 0;
    if (action == "buy") {
        newUnitPrice = (stockArray[index].unitPrice * (1 + (Math.pow(numStocksBought, 2) / 100)));
    }
    else if (action == "sell") {
        newUnitPrice = (stockArray[index].unitPrice * (1 - (Math.pow(numStocksBought, 2) / 100)));
    }

    newUnitPrice = Math.floor(newUnitPrice);
    stockArray[index].unitPrice = newUnitPrice;
    everyone.now.receiveStocks(stockArray);
}

everyone.now.getStockList = function () {
    this.now.receiveStocks(stockArray);
}

everyone.now.sGetName = function () {
    this.now.cGetName(this.now.name);
}

nowjs.on('connect', function () {
    console.log("Joined: " + this.now.name);
    everyone.now.reportUserStatus(this.now.name, "joined");
});


nowjs.on('disconnect', function () {
    console.log("Left: " + this.now.name);
    everyone.now.reportUserStatus(this.now.name, "left");
});




//end game stuff


//timer stuff

var initialTimer = false;
var timerRunning = false;
var gameTime = 20000 //3600000; //an hour (i think :p)
var timerStart = 0;
var timeRemaining = 0;


everyone.now.runTimer = function () {
    if (initialTimer == false) {
        timerStart = (new Date()).getTime();
        initialTimer = true;

        console.log("GameTime: " + gameTime);

        var intVal = setInterval(function () { setTimeout(everyone.now.updateTimer, 1000); }, 1000);
        setInterval((function () { clearInterval(intVal) }), gameTime);
    }

    if (timerRunning == false) {
        setInterval(function () {
            everyone.now.findWinner();
            setTimeout(function () {
                var winner = "";
                var highScore = 0;
                console.log("arr len " + userArray.length);
                for (var i = 0; i < userArray.length; i++) {
                    console.log("winner loop: " + userArray[i].username);
                    if (userArray[i].score > highScore) {
                        winner = userArray[i].username;
                    }
                }
                console.log("winner: " + winner);

                everyone.now.announceWinner(winner);
                userArray.length = 0;
                everyone.now.resetUserCredit();
                everyone.now.clearUserArray();
            }, 3000);

            timerStart = (new Date()).getTime();
            console.log("GameTime: " + gameTime);

            var intVal = setInterval(function () { setTimeout(everyone.now.updateTimer, 1000); }, 1000);
            setInterval((function () { clearInterval(intVal) }), gameTime);
        }, gameTime);
        timerRunning = true;
    }
}

everyone.now.updateTimer = function (ms) {
    everyone.now.displayTime(getRemTime());
};

everyone.now.sendScoreToServer = function (score) {
    userArray.push(new userScore(this.now.name, score));
}

function getRemTime() {
    var remMs = gameTime - (new Date().getTime() - timerStart);
    var remSec = remMs / 1000;
    var min = parseInt(remSec / 60);
    var sec = parseInt(remSec % 60);
    var jsonTime = '{"time":[{"min":"' + min + '","sec":"' + sec + '","gameTime":"' + (gameTime / 1000) + '" }]}';
    return jsonTime;
}



//end timer stuff